package com.winhxd.b2c.admin.utils;

import com.qcloud.Utilities.Json.JSONObject;
import com.winhxd.b2c.common.domain.product.vo.ProductSpuVideoVO;
import com.winhxd.b2c.common.domain.system.video.condition.VideoCondition;
import com.winhxd.b2c.common.domain.system.video.vo.MediaVO;
import com.winhxd.b2c.common.domain.system.video.vo.VideoInfoVO;
import com.winhxd.b2c.common.util.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @Description
 * @Author yuluyuan
 * @Date 2019/1/11 19:55
 **/
@Component
public class QcloudUtils {


    private static final Logger LOGGER = LoggerFactory.getLogger(QcloudUtils.class);

    private static final long UPLOAD_FILE_SIZE = 20L * 1024 * 1024;
    private static final String UPLOAD_DIR = "/opt/htv-video-tmp/upload";//TODO yuluyuan 这是Linux上的地址，需要更换。
    private static final String ERROR = "error";

    public MediaVO uploadVideo(MultipartFile videoFile, Model model) {

        MediaVO vo = new MediaVO();

        // 上传文件不能为空
        if (videoFile == null || StringUtils.isEmpty(videoFile.getOriginalFilename())) {
            model.addAttribute(ERROR, "请选择上传文件！");
            return vo;
        }
        if(videoFile.getSize() > UPLOAD_FILE_SIZE){
            model.addAttribute(ERROR, "文件不能超过20M");
            return vo;
        }

        // 获得原始文件名
        String name = videoFile.getOriginalFilename();
        String videoUrl = null;

        // 保存视频信息到本地
        File dir = new File(UPLOAD_DIR);
        try {
            //创建临时文件夹
            FileUtil.forceMkdir(dir);
        } catch (IOException e) {
            LOGGER.error("创建文件夹失败", e);
        }
        // 保存的文件名
        String saveFile = UPLOAD_DIR + File.separator + name;
        try {
            FileUtil.copyInputStreamToFile(videoFile.getInputStream(), new File(saveFile));
        } catch (IOException e) {
            LOGGER.error("保存视频信息到本地失败", e);
        }

        // 上传到腾讯云
        if(name.contains("\\.")){
            model.addAttribute(ERROR, "文件名称不规范，请上传正确文件！");
            return vo;
        }
        String fileId = VodUpload.upload(name.split("\\.")[0], name.split("\\.")[1], saveFile);
        LOGGER.info("from cloud fileId = " + fileId );
        if(StringUtils.isEmpty(fileId)){
            try {
                // 删除原视频文件
                FileUtil.deleteFile(saveFile);
            } catch (IOException e) {
                LOGGER.error("上传失败", e);
            }
            model.addAttribute(ERROR, "上传文件失败，请重新上传文件！");
            return vo;
        }

        if (StringUtils.isNotEmpty(fileId)) {
            // 设置腾讯视频ID
            vo.setFileId(fileId);
            LOGGER.info("ConvertVodFile start");
            // 腾讯云转码
            VodUpload.videoConvertVodFile(fileId);
            LOGGER.info("ConvertVodFile end");

            LOGGER.info("videoDescribeVodInfo start :获取视频时长");
            int duration = VodUpload.videoDescribeVodInfo(fileId,UPLOAD_DIR + File.separator);
            LOGGER.info("videoDescribeVodInfo end :获取视频时长,duration = " +duration);

            // 视频播放时长
            vo.setVideoDuration(duration);
            // 说明转码成功
            if (duration != 0) {
                LOGGER.info("videoDescribeVodPlayUrls :获取视频时长success");
                videoUrl = VodUpload.videoDescribeVodPlayUrls(fileId);
                LOGGER.info("set video Urls 视频地址 =" + videoUrl);
                vo.setMediaUrl(videoUrl);
                //成功
                vo.setRetCode("0");
                vo.setRetMsg("成功");
            }else{
                //失败
                vo.setRetCode("1");
                vo.setRetMsg("失败");
                model.addAttribute(ERROR, "视频转码失败，请重新添加视频！");
                return vo;
            }
        }

        try {
            // 删除原视频文件
            FileUtil.deleteFile(saveFile);
        } catch (IOException e) {
            LOGGER.info("原视频文件删除失败！");
        }

        LOGGER.info("视频上传成功！" + JsonUtil.toJSONString(vo));
        return vo;
    }

}
